<template>
    <div class="common" id="content">
      <div class="chat" >
          <div class="title">

              <div class="headPortrait">
                  <img :src="personInfor.portraitUri" alt="">
              </div>
              <div class="user-name">
                 {{personInfor.name}}
              </div>
              <router-link to="/app/chatPage/fixCode?code=D3C8A8E486C7460B949A3A57A089A5D7">
                  <div class="user-name" style="margin-top: 30px">
                          <img src="./../assets/images/Combined Shape.png" alt="">
                          <span class="number">{{unReadMessageNumber}}</span>
                  </div>
              </router-link>
              <router-link to="/app/module/waitCode">
                  <div  class="codeList">
                      <img src="./../assets/images/contact.png" alt="">
                  </div>
              </router-link>
              <router-link to="/app/module/waitCode">
                  <div  class="codeList">
                      <img src="./../assets/images/module.png" alt="">
                  </div>
              </router-link>
          </div>
          <div class="route">
              <router-view></router-view>
          </div>

      </div>

    </div>
</template>
<script>
  import RonrIM from './../service/RoneIM -Service'
  import User from './../service/User-Service'
  import Message from './../service/Message-Service'
  const _RonrIM = new RonrIM();
  const  _User = new User();
  const _Message = new Message();
    export default {
       data(){
         return {
           code:this.$util.getQueryString('code'),
           unReadMessageNumber:this.$store.state.unreadMessageNumber,
           personInfor:{},
           params:{
             code:this.$util.getQueryString('code') //D3C8A8E486C7460B949A3A57A089A5D7
           },
           chatObject:this.$store.state.chatObject
         }
       },
      created(){
        this._getTokenAndappKey();
      },
      mounted(){

      },
      methods:{
        _getTokenAndappKey () {
          let params = {
            code: this.code,
            portraitUri: '',
            name: '',
            remark: '',
            sign: ''
          };
          _RonrIM.getTokenAndKey(params).then((res)=>{
            let token = res.token;
            let appKey = res.appKey;
            this._initConnect(token, appKey);

          });

        },
        _initConnect (token, appKey) {
          let _this = this;
          // 连接状态监听器
          RongIMLib.RongIMClient.init(appKey);
          _RonrIM.setConnectionStatusListener();
          _RonrIM.RongIMClientConnect(token).then(()=>{
            _User.getUserList(this.params).then((data)=>{
              _User.setUserDataInit(data,'isTalking');
              //console.log(data.content)
             // data.content = RongIMLib.RongIMEmoji.emojiToHTML(data.content);
              data.forEach((item)=>{
                item.content = RongIMLib.RongIMEmoji.emojiToHTML(item.content);
                item.unreadMessageNumber = 0;
              });
              this.$store.dispatch('changeUserList',data);
            });
            _RonrIM.getTotalUnreadCount().then((count)=>{
              this.$store.dispatch('changeUnReadMessageNumber',count);
            })
          });
          // 消息监听器
          RongIMClient.setOnReceiveMessageListener({
            onReceived: (message) => {
              _this.messageReceive(message);
              console.log(message)

            }
          });

        },
        messageReceive(message){

          // 判断消息 是否跟当前聊天的人是同一个
          if(message.senderUserId === this.chatObject.code){
            // todo 要把当前消息变为已读
            _RonrIM.clearUnreadCount(message.senderUserId);
            this.$store.dispatch('changeChatContent',[message]);
          }else if(message.senderUserId !== 'sysim'){
            this._messageToOther(message)
          }
          // todo 推送消息是 用户 上线 跟离线 时处理

        },
        //如果消息不是跟当前的这个人聊天 1、 判断左边列表是否有这个人 2 、如果没有 就把当前这个聊天对象放在列表里面
        _messageToOther(message){
          let userList = this.$store.state.chatList;
          let hasUserFlag = false;
          for(let i = 0;i<userList.length;i++){
            let userInfor = userList[i];
            console.log(message);
            //判读当前消息是否在用户列表里面 todo 数据更新时检查是否更新
            if(userInfor.code === message.senderUserId){
                  userInfor.content = message.content.content;
                  userInfor.sendTime = message.sentTime;
                  userInfor.unreadMessageNumber++;
                  hasUserFlag = true;
              break
            }
          }
          //如果不在就把当前数据放在左边列表里
          if(!hasUserFlag){
            let obj  = {};
            obj.content = message.content.content;
            obj.msgType = message.msgType;
            obj.sendTime = message.sentTime;
            obj.unreadMessageNumber = 1;
            obj.senderUserId = message.senderUserId;
            obj.isTalking = false;
            obj.status = 0;
            userList.push(obj)
          }

          this.$store.dispatch('changeUserList',userList);
          //同时执行一下获取所有的未读消息数量
          _RonrIM.getTotalUnreadCount().then((count)=>{
            this.$store.dispatch('changeUnReadMessageNumber',count);
          })
        },
        goCodeList(){
          this.$router.push({path:"/app/codeList"})
        }
      },
      computed: {
        unreadMessageNumber() {
          return this.$store.state.unreadMessageNumber;
        },
        getChatObject(){
          return this.$store.state.chatObject;
        },
        getPersonInfor() {
          return this.$store.state.personInfor;
        }
      },
      watch: {
        unreadMessageNumber: function(a, b) {
          this.unReadMessageNumber = a;
        },
        getPersonInfor:function (a,b) {
          this.personInfor = a;
        },
        getChatObject:function(a){
          this.chatObject = a;
        }
      },
    }
</script>
<style scoped lang="scss" type="text/scss">
    .common{
        width: 100%;
        height: 100%;
        .chat{
            width:100%;
            height: 100%;
            display: flex;
            flex-direction: row;
            .title{
                width: 55px;
                position: relative;
                box-sizing: border-box;
                background: rgba(67,121,179,1);
                padding-top: 15px;
                .headPortrait{
                    img{
                        width: 30px;
                        height: 30px;
                    }
                }
                .user-name{
                    margin-top: 10px;
                    font-size: 12px;
                    color: #ffffff;
                    position: relative;
                    cursor: pointer;
                    img{
                        height: 20px;
                        width: 25px;
                    }
                    .number{
                        position: absolute;
                        display: block;
                        width: 20px;
                        height: 20px;
                        border-radius: 20px;
                        background: red;
                        text-align: center;
                        line-height: 20px;
                        right: 2px;
                        top: -10px;
                        font-size: 12px;
                    }
                }
                .codeList{
                    margin-top: 40px;
                    cursor: pointer;
                    color: #000000;
                  
                }

            }
            .route{
                flex: 1;
            }
        }

    }
</style>